﻿using iMES.Core.Utilities;
using iMES.Entity.DomainModels;
using iMES.Mass.IRepositories;
using iMES.Mass.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iMES.Mass.Services
{
    public partial class Mass_IncomingService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IMass_IncomingRepository _mass_IncomingRepository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public Mass_IncomingService(
            IHttpContextAccessor httpContextAccessor,
            IMass_IncomingRepository mass_IncomingRepository) : base(mass_IncomingRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _mass_IncomingRepository = mass_IncomingRepository;
        }
        WebResponseContent webResponse = new WebResponseContent();
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            AddOnExecuting = (Mass_Incoming incoming, object list) =>
            {
                incoming.Mass_Incoming_Code = GetMass_DetectionItemsCode(incoming);
                if (repository.Exists(x => x.Mass_Incoming_Code == incoming.Mass_Incoming_Code))
                {
                    return webResponse.Error("来料检验单编号已存在");
                }
                return webResponse.OK();
            };
            return base.Add(saveDataModel);
        }
        /// <summary>
        /// 自动生成编码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string GetMass_DetectionItemsCode(Mass_Incoming model)
        {
            // 若有编码，则直接返回
            if (!string.IsNullOrEmpty(model.Mass_Incoming_Code))
            {
                return model.Mass_Incoming_Code;
            }
            else
            {
                // 自动生成编码
                var list = Mass_IncomingRepository.Intance.FindAsIQueryable
                    (x => x.Mass_Incoming_Code.StartsWith("LLJYD")).OrderByDescending(x => x.Mass_Incoming_Code).ToList().FirstOrDefault();
                if (list == null)
                {
                    return "LLJYD" + "00001";
                }
                else
                {
                    //LLJYD0001
                    string code = list.Mass_Incoming_Code.Substring(5, 5);
                    int num = int.Parse(code) + 1;
                    return "LLJYD" + num.ToString().PadLeft(5, '0');
                }
            }
        }
    }
}
